/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

/**
 *
 * @author mszankin
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import core.Security;
import core.User;

public class Database {
	private Connection conn = null;
	private String database;
	private String user;
	private String password;
	private String host;

	public Database(String database, String user, String password, String host) {
		this.database = database;
		this.user = user;
		this.password = password;
		this.host = host;
	}
	
	public List<User> getUsersList() {
		List<User> userList = new ArrayList<User>();
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT username, password FROM users");
			while (rs.next()) {
				userList.add(new User(rs.getString(1), rs.getString(2)));
			}

		} catch (SQLException ex) {
			// handle any errors
			 this.appendToLog("SQLException: " + ex.getMessage());
			 this.appendToLog("SQLState: " + ex.getSQLState());
			 this.appendToLog("VendorError: " + ex.getErrorCode());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
				}
				rs = null;
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlEx) {
				}
				stmt = null;
			}
		}
		
		return userList;
	}
	
	public boolean newUser(String username, String password){
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			ResultSet resultSet = stmt.executeQuery("SELECT username FROM users");
			while (resultSet.next()) {
				if(resultSet.getString(1).equals(username)){
					 this.appendToLog("Rejestracja uzytkownika NIE powiodla sie: "+ username);
					 return false;
				 }
			}
			stmt.executeUpdate("INSERT INTO users(username, password) VALUES ('" + username + "', '"+ Security.stringHash(password) +"')");
		} catch (SQLException ex) {
			// handle any errors
			 this.appendToLog("SQLException: " + ex.getMessage());
			 this.appendToLog("SQLState: " + ex.getSQLState());
			 this.appendToLog("VendorError: " + ex.getErrorCode());
			 this.appendToLog("Rejestracja uzytkownika NIE powiodla sie: "+ username);
			 return false;
		}
			this.appendToLog("Nowy uzytkownik zarejestrowany poprawnie: "+ username + " @ " + Security.stringHash(password));
		
		return true;
	}

        public boolean checkIfUsernameIsTaken(String username) {
		Statement stmt = null;
		ResultSet rs = null;
		boolean result = false;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT username FROM users");
			while (rs.next()) {
				 if(rs.getString(1).equals(username)){
					 result=true;
					 this.appendToLog("Nazwa uzytkownika zajeta: "+ username);
				 }
			}

		} catch (SQLException ex) {
			// handle any errors
			 this.appendToLog("SQLException: " + ex.getMessage());
			 this.appendToLog("SQLState: " + ex.getSQLState());
			 this.appendToLog("VendorError: " + ex.getErrorCode());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
				}
				rs = null;
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlEx) {
				}
				stmt = null;
			}
		}
		if(result == false)
			this.appendToLog("Nazwa uzytkownika wolna: "+ username);
		
		return result;
	}
        
	public boolean authUser(String username, String password) {
		Statement stmt = null;
		ResultSet rs = null;
		boolean result = false;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT username, password FROM users");
			while (rs.next()) {
				 if(rs.getString(1).equals(username) && rs.getString(2).equals(Security.stringHash(password))){
					 result=true;
					 this.appendToLog("User auth positive for: "+ username + " @ " + Security.stringHash(password));
				 }
			}

		} catch (SQLException ex) {
			// handle any errors
			 this.appendToLog("SQLException: " + ex.getMessage());
			 this.appendToLog("SQLState: " + ex.getSQLState());
			 this.appendToLog("VendorError: " + ex.getErrorCode());
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
				}
				rs = null;
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlEx) {
				}
				stmt = null;
			}
		}
		if(result == false)
			this.appendToLog("User auth negative for: "+ username);
		
		return result;
	}

	private boolean createInstanceJDBC() {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			this.appendToLog("Stworzono instancje JDBC.");
			return true;
		} catch (Exception ex) {
			this.appendToLog("Blad: !(Stworzono instancje JDBC.)");
			return false;
		}
	}

	public boolean connectMySQL() {
		if (false == this.createInstanceJDBC())
			return false;

		try {
			this.conn = DriverManager.getConnection("jdbc:mysql://"+this.host+"/"
					+ this.database + "?user=" + this.user + "&password="
					+ this.password);
			 appendToLog("Polaczono z baza danych!");

			return true;
		} catch (SQLException ex) {
			this.appendToLog("SQLException: " + ex.getMessage());
			this.appendToLog("SQLState: " + ex.getSQLState());
			this.appendToLog("VendorError: " + ex.getErrorCode());

			return false;
		}
	}
	//SAADEQQI
	private void appendToLog(String msg) {
		System.out.println("\n" + msg);
	}
}